<?php

namespace app\common\model;

use app\common\helper\util\Tool;
use eduline\upload\Client as FileClient;
use eduline\upload\utils\Util;
use Exception;
use think\facade\Request;
use think\model\concern\SoftDelete;

/**
 * 附件数据库定义
 */
class Attach extends BaseModel
{
    /**
     * 使用软删除
     */
    use SoftDelete;

    /**
     * 定义删除的字段
     *
     * @var string
     */
    protected $deleteTime = 'delete_time';
    /**
     * 设置自动写入时间
     *
     * @var boolean
     */
    protected $autoWriteTimestamp = true;
    /**
     * 不写入更新时间
     *
     * @var boolean
     */
    protected $updateTime = false;
    /**
     * 定义字段类型
     *
     * @var array
     */
    protected $type = [
        'create_time' => 'timestamp:Y-m-d H:i:s',
        'delete_time' => 'timestamp:Y-m-d H:i:s',
        'filedata'    => 'json',
        'id'          => 'integer',
    ];

    /**
     * 字段填充
     *
     * @var [type]
     */
    protected $append = ['duration_format'];

    /**
     * 设置扩展类型
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2019-11-12
     *
     * @param string $extension 扩展类型
     * @param array  $data      源数据
     */
    protected function setExtensionAttr($extension, $data)
    {
        if (!$extension) {
            $extension = strtolower(substr(strrchr($data['savename'], '.'), 1));
        }

        return $extension;
    }

    /**
     * 文件大小转换
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2019-11-12
     *
     * @param    [type]                         $size [description]
     * @return string [type]                               [description]
     */
    protected function getFilesizeAttr($size)
    {
        $arr = ["B", "KB", "MB", "GB", "TB", "PB"];
        $pos = 0;
        while ($size >= 1024) {
            $size /= 1024;
            $pos++;
        }

        return round($size, 2) . " " . $arr[$pos];

    }

    /**
     * 获取文件的保存地址
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2019-11-13
     *
     * @param $value
     * @param $data
     * @return string [type]                                [description]
     */
    protected function getFilepathAttr($value, $data)
    {
        if (!isset($data['stock'])) {
            return '';
        }
        $file = new FileClient($data['stock']);

        return $file->path($data);
    }

    /**
     * 获取文件的访问url
     * Author Martinsun<syh@sunyonghong.com>
     * Date 2019-11-13
     *
     * @param $value
     * @param $data
     * @return string [type] [description]
     * @throws Exception
     */
    protected function getFileurlAttr($value, $data)
    {
        if (!isset($data['stock']) || !isset($data['mimetype'])) {
            return '';
        } else if ($this->isImage($data['mimetype'])) {
            $url = $data['view_url_expire'] < time() ? '' : ($data['view_url'] ?? '');

            return $url ?: $this->getAttachViewUrl($data['id']);
        }

        $file = new FileClient($data['stock']);

        return $file->url($data);
    }

    /**
     * 附件的条件地址
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/8/4
     *
     * @param $value
     * @param $data
     * @return string
     */
    protected function getRedirectUrlAttr($value, $data)
    {
        if (!isset($data['stock'])) {
            return '';
        }

        $url = $data['view_url'] ?? '';
        if (!$url || $data['view_url_expire'] < time()) {
            $file = new FileClient($data['stock']);

            $url = $file->url($data);

            if ($data['stock'] != 'local' && $this->isImage($data['mimetype'])) {
                // 更改图片地址
                Attach::update(['view_url' => $url, 'view_url_expire' => time() + 3300], ['id' => $data['id']]);
            }
        }

        return $url;
    }

    /**
     * 处理时间格式
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-08-18
     *
     * @param $value
     * @param $data
     * @return string [type]                                [description]
     */
    protected function getDurationFormatAttr($value, $data)
    {
        return Tool::secsToColonStr($data['duration']);
    }

    /**
     * 获取附件预览的地址
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/6/3
     *
     * @param int $attachId
     * @return string
     * @throws Exception
     */
    public function getAttachViewUrl(int $attachId)
    {
        return Request::domain() . '/attach/' . Tool::encodeId($attachId);
    }

    /**
     * 是否是图片
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/8/4
     *
     * @param string $mimetype
     * @return bool
     */
    public function isImage(string $mimetype)
    {
        return Util::isImage($mimetype);
    }

}
